<?php

namespace App\Http\Controllers;

use App\Models\VerificationCode;
use App\Models\Product;
use App\Models\UserToken;
use App\Models\ShippingAddress;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class ExchangeController extends Controller
{
    // 在类的开始处添加生成订单编号的方法
    private function generateOrderNumber()
    {
        // 生成年月日时分秒，14位
        $datePrefix = date('YmdHis');
        
        // 生成4位随机数（1000-9999）
        $randomNumber = mt_rand(1000, 9999);
        
        // 组合订单编号（14位时间 + 4位随机数 = 18位）
        $orderNumber = $datePrefix . $randomNumber;
        
        // 检查订单编号是否已存在，如果存在则重新生成随机数部分
        while (Order::where('order_number', $orderNumber)->exists()) {
            $randomNumber = mt_rand(1000, 9999);
            $orderNumber = $datePrefix . $randomNumber;
        }
        
        return $orderNumber;
    }

    public function exchange(Request $request)
    {
        // 记录接收到的兑换请求
        Log::info('收到兑换请求', [
            'request_data' => $request->all(),
            'headers' => $request->header()
        ]);

        try {
            // 验证请求数据
            $validated = $request->validate([
                'code' => [
                    'required',
                    'string',
                    'size:12',
                    'regex:/^[A-HJ-KMN-Z2-9]+$/',
                ],
                'receiverName' => 'required|string|max:50',
                'receiverPhone' => [
                    'required',
                    'regex:/^1[3-9]\d{9}$/'    // 简化规则，只保留最必要的验证
                ],
                'receiverAddress' => 'required|string|max:255'
            ], [
                'code.required' => '兑换码不能为空',
                'code.size' => '兑换码必须是12位',
                'code.regex' => '兑换码格式不正确，只能包含大写字母和数字，且不能包含I、L、O、0、1',
                'receiverPhone.required' => '手机号码不能为空',
                'receiverPhone.regex' => '手机号码格式不正确'
            ]);

            // 验证token
            $token = str_replace('Bearer ', '', $request->header('Authorization'));
            
            if (empty($token)) {
                Log::warning('兑换失败：未提供token');
                return response()->json([
                    'success' => false,
                    'message' => '请先登录'
                ], 200);
            }

            // 检查token是否存在且在有效期内
            $userToken = UserToken::where('token', $token)
                    ->where('expired_at', '>', Carbon::now())
                    ->first();

            if (!$userToken) {
                Log::warning('兑换失败：token无效或已过期', [
                    'token' => $token
                ]);
                return response()->json([
                    'success' => false,
                    'message' => 'token已过期，请重新登录'
                ], 200);
            }

            // 查询验证码
            $verificationCode = VerificationCode::with(['codeActivity.product'])
                ->where('code', $validated['code'])
                ->first();

            // 添加调试日志
            Log::info('验证码和关联数据', [
                'verification_code' => $verificationCode ? [
                    'id' => $verificationCode->id,
                    'code' => $verificationCode->code,
                    'code_activity' => $verificationCode->codeActivity ? [
                        'id' => $verificationCode->codeActivity->id,
                        'product' => $verificationCode->codeActivity->product ? [
                            'id' => $verificationCode->codeActivity->product->id,
                            'name' => $verificationCode->codeActivity->product->name
                        ] : 'no product'
                    ] : 'no activity'
                ] : 'no verification code'
            ]);

            // 获取商品信息
            if (!$verificationCode->codeActivity) {
                Log::error('兑换失败：活动不存在', [
                    'verification_code_id' => $verificationCode->id
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '兑换活动不存在'
                ], 200);
            }

            $product = $verificationCode->codeActivity->product;

            if (!$product) {
                Log::error('兑换失败：商品不存在', [
                    'verification_code_id' => $verificationCode->id,
                    'code_activity_id' => $verificationCode->code_activity_id
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '商品信息无效'
                ], 200);
            }

            // 检查验证码是否已使用
            if ($verificationCode->is_used) {
                // 检查是否是当前用户使用的
                if ($verificationCode->wechat_user_id === $userToken->wechat_user_id) {
                    Log::info('验证码已被当前用户兑换', [
                        'code' => $validated['code'],
                        'user_id' => $userToken->wechat_user_id
                    ]);
                    return response()->json([
                        'success' => false,
                        'message' => '该兑换码已经被您兑换，请查看我的订单'
                    ], 200);
                } else {
                    Log::warning('兑换失败：验证码已被他用户使用', [
                        'code' => $validated['code']
                    ]);
                    return response()->json([
                        'success' => false,
                        'message' => '该兑换码已被使用'
                    ], 200);
                }
            }

            // 检查验证码是否过期
            if ($verificationCode->expired_at < Carbon::now()) {
                Log::warning('兑换失败：验证码已过期', [
                    'code' => $validated['code'],
                    'expired_at' => $verificationCode->expired_at
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '验证码已过期'
                ], 200);
            }

            // 检查商品是否可用
            if (!$product->is_active) {
                Log::warning('兑换失败：商品已下架', [
                    'product_id' => $product->id
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '该商品已下架'
                ], 200);
            }

            // 保存收货地址
            // 先检查用户是否已有地址
            $hasAddress = ShippingAddress::where('wechat_user_id', $userToken->wechat_user_id)->exists();
            
            $shippingAddress = ShippingAddress::create([
                'wechat_user_id' => $userToken->wechat_user_id,
                'receiver_name' => $validated['receiverName'],
                'receiver_phone' => $validated['receiverPhone'],
                'receiver_address' => $validated['receiverAddress'],
                'is_default' => !$hasAddress  // 如果是用户第一个地址，设为默认
            ]);

            // 在创建订单之后，更新商品销量
            try {
                // 将所有需要的变量先获取和验证
                $productId = $verificationCode->codeActivity->product->id;
                $productToUpdate = Product::findOrFail($productId);  // 重新获取商品实例

                DB::transaction(function () use ($productToUpdate, $verificationCode, $userToken, $shippingAddress) {
                    // 创建订单
                    $order = Order::create([
                        'order_number' => $this->generateOrderNumber(),
                        'wechat_user_id' => $userToken->wechat_user_id,
                        'product_id' => $productToUpdate->id,  // 使用新获取的商品ID
                        'verification_code_id' => $verificationCode->id,
                        'shipping_address_id' => $shippingAddress->id,
                        'status' => 0  // 待发货状态
                    ]);

                    // 更新验证码状态
                    $verificationCode->update([
                        'is_used' => true,
                        'wechat_user_id' => $userToken->wechat_user_id
                    ]);

                    // 更新商品销量
                    $productToUpdate->increment('sales_count');

                    // 记录兑换成功
                    Log::info('兑换成功', [
                        'user_id' => $userToken->wechat_user_id,
                        'order_id' => $order->id,
                        'order_number' => $order->order_number,
                        'product_id' => $productToUpdate->id,
                        'old_sales_count' => $productToUpdate->sales_count - 1,
                        'new_sales_count' => $productToUpdate->sales_count
                    ]);

                    // 将订单号保存到外部变量，以便返回
                    $this->orderNumber = $order->order_number;
                });

                // 返回成功响应
                return response()->json([
                    'success' => true,
                    'message' => '兑换成功',
                    'data' => [
                        'order_number' => $this->orderNumber
                    ]
                ]);

            } catch (\Exception $e) {
                Log::error('更新商品销量失败', [
                    'verification_code_id' => $verificationCode->id,
                    'code_activity_id' => $verificationCode->code_activity_id,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
                throw $e;
            }

        } catch (\Exception $e) {
            Log::error('兑换过程发生异常', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => '服务器错误，请稍后重试'
            ], 200);
        }
    }
} 